import React, { useState, useEffect, useMemo, memo } from 'react';
import styles from './index.less';
import useModel from '../../useModels/useModel.js';
import Connect from '@/components/Connect';
import IconFont from '@/components/IconFont';
import Toolbar from '@/components/Toolbar';
import { useLocalStorageState } from '@umijs/hooks';
import { message } from 'antd';
import useAddModel from '../../useModels/useAddModel';
import RealtimeMessage from '../RealtimeMessage';
import useRealtimeMessage from '../../useModels/useRealtimeMessage';
import Stomp from 'stompjs';
import SockJS from 'sockjs-client';
import { getWsAddr } from '../../service.js';

export const createSocket = (updateRecord, dispatch, ip) => {
  if (!ip) {
    return;
  }
  let socket = null;
  let stompClient = null;
  const connect = () => {
    socket = new SockJS(`http://${ip}:9999/websocket`); //WebSocket对应的地址

    stompClient = Stomp.over(socket);
    //定义连接函数
    if (stompClient == null || !stompClient.connected) {
      const headers = {};
      stompClient.reconnect_delay = 20000;
      stompClient.heartbeat.outgoing = 20000;
      stompClient.heartbeat.incoming = 0;
      stompClient.connect(headers, connectCallback, errorCallback);
    } else {
      console.log('当前处于连接状态');
    }
  };
  const connectCallback = frame => {
    dispatch({ socket: stompClient });
    //连接成功时的回调函数
    console.log('Connected: ' + frame);
    //订阅AAA频道
    stompClient.subscribe('/topic/terminal', function(greeting) {
      //后台传过来的json字符串转换为json对象

      if (greeting.body) {
        const obj = JSON.parse(greeting.body);
        updateRecord(obj);
      }
    });
  };
  const errorCallback = () => {
    //连接失败时的回调函数，此函数重新调用连接方法，形成循环，直到连接成功
    connect();
  };
  connect();
};

const ToolbarWrap = ({ importConfigProps }) => {
  const [currentDeviceType] = useLocalStorageState('deviceType');
  const { setVisible, getDeviceType } = useAddModel(() => []);
  const {
    setVisible: setRealtimeVisible,
    dispatch,
    updateRecord,
    record,
  } = useRealtimeMessage(model => [model.record]);

  let toolbar = [
    {
      type: 'button',
      name: '新增',
      icon: <IconFont type={'iconxinzeng'} />,
      onClick: () => {
        getDeviceType();
        setVisible(true);
      },
    },
    {
      type: 'button',
      theme: 'white',
      name: '实时报文',
      icon: <IconFont type={'iconshishibaowen'} />,
      onClick: async () => {
        let wsAddr = await getWsAddr();
        createSocket(updateRecord, dispatch, wsAddr?.data?.ip);
        setRealtimeVisible(true);
      },
    },
    {
      type: 'upload',
      buttonName: '导入电信配置',
      pos: 'right',
      name: 'file',
      theme: 'white',
      accept: 'text/xml,application/xml',
      showUploadList: false,
      className: styles['import-wrap'],
      icon: <IconFont type={'icondaoru'} />,
      beforeUpload: file => {
        if (file.type != 'text/xml') {
          message.error('请选择xml文件');
          return false;
        }
        let formData = new FormData();
        formData.append('fsuTypeId', currentDeviceType?.id);
        formData.append('file', file);
        importConfigProps.run(formData);

        return false;
      },
    },
  ];

  return (
    <>
      <Toolbar modules={toolbar} leftSpan={16} fields={{}} className={styles['toolbar-wrap']} />
      <RealtimeMessage />
    </>
  );
};
export default Connect(state => {
  return { importConfigProps: state.importConfigProps };
}, useModel)(ToolbarWrap);
